/**
 * 股票关注管理Hook
 */

import { useState, useEffect, useCallback } from 'react'
import { api, useApiCall } from '../api'

/**
 * 关注列表项
 */
export interface WatchedStockItem {
  id: number | string
  stockCode: string
  stockName: string | null
  watchTime: string
  currentPrice: number | null
  changePercent: number | null
  createdAt: string
  // 新增字段，与全部股票推荐字段保持一致
  volume: number | null
  prevVolume: number | null
  energyValue: number | null
  holdingDays: number | null
  watchId: number | null
  score: number | null  // 股票强度评分
}

/**
 * 股票关注Hook
 */
export function useWatch() {
  const [watchedStocks, setWatchedStocks] = useState<string[]>([])
  const [watchedStockDetails, setWatchedStockDetails] = useState<WatchedStockItem[]>([])

  // 获取关注列表
  const { execute: fetchWatchedStocks, isLoading: isFetching } = useApiCall(
    api.watch.getWatchedStocks,
    {
      showToast: false,
      onSuccess: (data: any[]) => {
        console.log('关注列表API返回数据:', data)
        
        // 处理数据，确保字段名正确映射
        const processedData = data.map((item, index) => ({
          id: item.watchId || item.id || `watch-${item.code || item.stockCode}-${index}`, // 使用watchId作为唯一ID
          stockCode: item.code || item.stockCode || item.stock_code,
          stockName: item.name || item.stockName || item.stock_name,
          watchTime: item.watchTime || item.watch_time || item.createdAt || new Date().toISOString(),
          currentPrice: item.currentPrice || item.current_price || null,
          changePercent: item.changePercent || item.change_percent || null,
          createdAt: item.createdAt || item.created_at || new Date().toISOString(),
          // 新增字段映射
          volume: item.volume !== undefined ? item.volume : null,
          prevVolume: item.prevVolume !== undefined ? item.prevVolume : null,
          energyValue: item.energyValue !== undefined ? item.energyValue : null,
          holdingDays: item.holdingDays !== undefined ? item.holdingDays : null,
          watchId: item.watchId !== undefined ? item.watchId : null,
          score: item.score !== undefined ? item.score : null  // 映射强度评分
        }))
        
        // 从处理后的数据中提取股票代码
        const stockCodes = processedData.map(item => item.stockCode).filter(Boolean)
        console.log('提取的股票代码:', stockCodes)
        console.log('处理后的数据:', processedData)
        
        setWatchedStocks(stockCodes)
        setWatchedStockDetails(processedData)
      },
      onError: (error) => {
        // 如果获取失败(比如未登录)，重置为空数组
        console.log('获取关注列表失败:', error)
        setWatchedStocks([])
        setWatchedStockDetails([])
      },
    }
  )

  // 移除自动初始化加载，改为按需加载
  // 由页面组件统一控制何时加载关注列表，避免重复请求

  // 添加关注
  const { execute: addToWatchlist, isLoading: isAdding } = useApiCall(
    api.watch.addToWatchlist,
    {
      showToast: true,
      onSuccess: () => {
        // 添加成功，不需要重新获取列表（已通过乐观更新处理）
        console.log('添加关注成功')
      },
    }
  )

  // 取消关注
  const { execute: removeFromWatchlist, isLoading: isRemoving } = useApiCall(
    api.watch.removeFromWatchlist,
    {
      showToast: true,
      onSuccess: () => {
        // 取消关注成功，不需要重新获取列表（已通过乐观更新处理）
        console.log('取消关注成功')
      },
    }
  )

  // 检查是否已关注
  const isWatched = useCallback(
    (stockCode: string) => {
      return watchedStocks.includes(stockCode)
    },
    [watchedStocks]
  )

  // 切换关注状态
  const toggle = useCallback(
    async (stockCode: string) => {
      const wasWatched = isWatched(stockCode)
      
      // 立即更新UI状态，提供快速反馈
      if (wasWatched) {
        setWatchedStocks(prev => prev.filter(code => code !== stockCode))
      } else {
        setWatchedStocks(prev => [...prev, stockCode])
      }
      
      try {
        if (wasWatched) {
          await removeFromWatchlist(stockCode)
        } else {
          await addToWatchlist(stockCode)
        }
      } catch (error) {
        // 如果API调用失败，回滚状态
        if (wasWatched) {
          setWatchedStocks(prev => [...prev, stockCode])
        } else {
          setWatchedStocks(prev => prev.filter(code => code !== stockCode))
        }
        throw error
      }
    },
    [isWatched, addToWatchlist, removeFromWatchlist]
  )

  // 手动刷新关注列表的方法（避免依赖循环）
  const refreshWatchlist = useCallback(() => {
    fetchWatchedStocks()
  }, [])

  // 将WatchedStockItem转换为AppStockRecommendation格式（用于统一使用StockCard组件）
  const convertToStockRecommendation = useCallback((item: WatchedStockItem) => {
    return {
      code: item.stockCode,
      name: item.stockName || item.stockCode,
      change_percent: item.changePercent || 0,
      volume: item.volume || 0,
      prev_volume: item.prevVolume || 0,
      energy_value: item.energyValue || 0,
      holding_days: item.holdingDays || 0,
      strength: item.score || undefined,
    }
  }, [])

  // 转换后的关注列表（AppStockRecommendation格式）
  const watchedStockRecommendations = watchedStockDetails.map(convertToStockRecommendation)

  return {
    watchedStocks,
    watchedStockDetails,
    watchedStockRecommendations,
    isWatched,
    toggle,
    isToggling: isAdding || isRemoving,
    isFetching,
    refresh: fetchWatchedStocks,
    refreshWatchlist,
  }
}